package com.sfj.system.service.jiekou;

import cn.hutool.system.UserInfo;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sfj.system.exception.LoginException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author kaka
 * @Date 2025/08/25
 */
@Slf4j
public class OAuthClient {

    private static String path = "http://25.120.128.13/sso-api";
    private static final ObjectMapper mapper = new ObjectMapper();

    // 获取 token
    public static String getToken(String clientId, String clientSecret, String code, String redirectUri) throws IOException {
        String url = path + "/oauth/token";
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);

        String params = "client_id=" + clientId +
                "&client_secret=" + clientSecret +
                "&code=" + code +
                "&grant_type=authorization_code" +
                "&redirect_uri=" + redirectUri;

        log.info("统一平台请求接口参数 {}", params);

        try (OutputStream os = conn.getOutputStream()) {
            os.write(params.getBytes(StandardCharsets.UTF_8));
        }

        String response = readResponse(conn);
        // 解析 access_token
        JsonNode jsonNode = mapper.readTree(response);
        String accessToken = null;
        try {
            accessToken = jsonNode.get("access_token").asText();
        } catch (Exception e) {
            log.error("统一平台获取access_token失败 {}", jsonNode.toString());
            throw new LoginException("统一平台获取access_token失败,json:" + jsonNode.toString());
        }
        return accessToken;
    }

    // 获取用户信息
    public static TongyiUserInfo getUserInfo(String accessToken) throws IOException {
        String url = path + "/userInfo";
        URL obj = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + accessToken);

        String response = readResponse(conn);
        JsonNode jsonNode = mapper.readTree(response);

        if (jsonNode.get("code").asInt() == 0) {
            // 请求成功
            JsonNode data = jsonNode.get("data");
            TongyiUserInfo user = new TongyiUserInfo();
            user.setId(data.get("id").asInt());
            user.setUserName(data.get("userName").asText());
            user.setLoginName(data.get("loginName").asText());
            user.setIdNo(data.get("idNo").asText());
            if (data.has("post")) user.setPost(data.get("post").asText());
            if (data.has("oaId")) user.setOaId(data.get("oaId").asText());
            if (data.has("phone")) user.setPhone(data.get("phone").asText());
            if (data.has("email")) user.setEmail(data.get("email").asText());
            JsonNode orgNode = data.get("org");
            if (orgNode != null) {
                TongyiOrg org = new TongyiOrg();
                org.setId(orgNode.get("id").asInt());
                org.setName(orgNode.get("name").asText());
                //org.setParent(orgNode.get("parent").asText());
                user.setOrg(org);
            }
            return user;
        } else {
            throw new RuntimeException("获取用户信息失败: " + jsonNode.get("msg").asText());
        }
    }

    // 工具方法：读取响应
    private static String readResponse(HttpURLConnection conn) throws IOException {
        int responseCode = conn.getResponseCode();
        if (responseCode == 502) {
            throw new LoginException("统一平台连接失败");
        }
        InputStream is = responseCode == 200 ? conn.getInputStream() : conn.getErrorStream();
        try (BufferedReader in = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line);
            }
            return sb.toString();
        }
    }


}
